package com.ruoyi.zsyh.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.ruoyi.common.utils.EmptyUtils;
import com.ruoyi.common.utils.K100Utils;
import com.ruoyi.common.utils.RedisUtil;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.zsyh.domain.ZsyhServiceOrderParts;
import com.ruoyi.zsyh.service.IZsyhServiceOrderPartsService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 师傅申请配件Controller
 * 
 * @author yuexl
 * @date 2022-09-06
 */
@Controller
@RequestMapping("/zsyh/serviceOrderParts")
public class ZsyhServiceOrderPartsController extends BaseController
{
    private String prefix = "zsyh/serviceOrderParts";

    @Autowired
    private IZsyhServiceOrderPartsService zsyhServiceOrderPartsService;
    @Autowired
    private RedisUtil redisUtils;
    @Autowired
    private K100Utils k100Utils;

    @RequiresPermissions("zsyh:serviceOrderParts:view")
    @GetMapping()
    public String serviceOrderParts()
    {
        return prefix + "/serviceOrderParts";
    }

    /**
     * 查询师傅申请配件列表
     */
    @RequiresPermissions("zsyh:serviceOrderParts:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(ZsyhServiceOrderParts zsyhServiceOrderParts)
    {
        startPage();
        List<ZsyhServiceOrderParts> list = zsyhServiceOrderPartsService.selectZsyhServiceOrderPartsList(zsyhServiceOrderParts);
        return getDataTable(list);
    }

    /**
     * 查询售后产品信息列表
     */
    @RequiresPermissions("zsyh:serviceOrderParts:list")
    @PostMapping("/listById")
    @ResponseBody
    public TableDataInfo listById(String id)
    {
        ZsyhServiceOrderParts zsyhServiceOrderParts = new ZsyhServiceOrderParts();
        zsyhServiceOrderParts.setOrderId(id);
        List<ZsyhServiceOrderParts> list = zsyhServiceOrderPartsService.selectZsyhServiceOrderPartsList(zsyhServiceOrderParts);
        return getDataTable(list);
    }

    /**
     * 导出师傅申请配件列表
     */
    @RequiresPermissions("zsyh:serviceOrderParts:export")
    @Log(title = "师傅申请配件", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(ZsyhServiceOrderParts zsyhServiceOrderParts)
    {
        List<ZsyhServiceOrderParts> list = zsyhServiceOrderPartsService.selectZsyhServiceOrderPartsList(zsyhServiceOrderParts);
        ExcelUtil<ZsyhServiceOrderParts> util = new ExcelUtil<ZsyhServiceOrderParts>(ZsyhServiceOrderParts.class);
        return util.exportExcel(list, "师傅申请配件数据");
    }

    /**
     * 新增师傅申请配件
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 修改服务订单
     */
    @GetMapping("/viewImage/{id}")
    public String viewImage(@PathVariable("id") String id, ModelMap mmap)
    {
        ZsyhServiceOrderParts zsyhServiceOrderParts = zsyhServiceOrderPartsService.selectZsyhServiceOrderPartsById(id);
        mmap.put("zsyhServiceOrderParts", zsyhServiceOrderParts);
        return prefix + "/viewImage";
    }

    /**
     * 新增保存师傅申请配件
     */
    @RequiresPermissions("zsyh:serviceOrderParts:add")
    @Log(title = "师傅申请配件", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(ZsyhServiceOrderParts zsyhServiceOrderParts)
    {
        return toAjax(zsyhServiceOrderPartsService.insertZsyhServiceOrderParts(zsyhServiceOrderParts));
    }

    /**
     * 修改师傅申请配件
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") String id, ModelMap mmap)
    {
        ZsyhServiceOrderParts zsyhServiceOrderParts = zsyhServiceOrderPartsService.selectZsyhServiceOrderPartsById(id);
        mmap.put("zsyhServiceOrderParts", zsyhServiceOrderParts);
        return prefix + "/edit";
    }

    /**
     * 修改保存师傅申请配件
     */
    @RequiresPermissions("zsyh:serviceOrderParts:edit")
    @Log(title = "师傅申请配件", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(ZsyhServiceOrderParts zsyhServiceOrderParts)
    {
        return toAjax(zsyhServiceOrderPartsService.updateZsyhServiceOrderParts(zsyhServiceOrderParts));
    }

    /**
     * 删除师傅申请配件
     */
    @RequiresPermissions("zsyh:serviceOrderParts:remove")
    @Log(title = "师傅申请配件", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(zsyhServiceOrderPartsService.deleteZsyhServiceOrderPartsByIds(ids));
    }

    /**
     * 判断物流单是否有配件信息
     * type=1邮寄新件
     * type=2返回旧件
     */
    @RequiresPermissions("zsyh:serviceOrderParts:edit")
    @Log(title = "判断物流单是否有配件信息", businessType = BusinessType.UPDATE)
    @PostMapping("/isLogistics")
    @ResponseBody
    public AjaxResult isLogistics(String orderPartsId, String type) throws Exception {
        ZsyhServiceOrderParts orderParts = zsyhServiceOrderPartsService.getServiceOrderPartsById(orderPartsId);
        String json = "";
        if("1".equals(type)){
            String logisticsJson = String.valueOf(redisUtils.get("logistics_" + orderPartsId));
            if(EmptyUtils.isNotEmpty(logisticsJson)){
                json = logisticsJson;
            }else{
                String logisticsId = orderParts.getLogisticsId();
                String logisticsNumber = orderParts.getLogisticsNumber();
                if(EmptyUtils.isEmpty(logisticsId) || EmptyUtils.isEmpty(logisticsNumber)){
                    return error("暂无物流信息");
                }
                json = k100Utils.queryTrack(logisticsId, logisticsNumber);
                JSONObject jsonObject = JSON.parseObject(json);
                String status = String.valueOf(jsonObject.get("status"));
                if("200".equals(status)){
                    redisUtils.set("logistics_" + orderPartsId, json, 1800);
                    orderParts = new ZsyhServiceOrderParts();
                    orderParts.setId(orderPartsId);
                    orderParts.setLogisticsJson(json);
                    zsyhServiceOrderPartsService.updateZsyhServiceOrderParts(orderParts);
                }else{
                    String returnCode = String.valueOf(jsonObject.get("returnCode"));
                    if(!"200".equals(returnCode)){
                        String message = String.valueOf(jsonObject.get("message"));
                        return error(message);
                    }
                }
            }

        }else{
            String logisticsJson = String.valueOf(redisUtils.get("return_logistics_" + orderPartsId));
            if(EmptyUtils.isNotEmpty(logisticsJson)){
                json = logisticsJson;
            }else{
                String returnLogisticsId = orderParts.getReturnLogisticsId();
                String returnLogisticsNumber = orderParts.getReturnLogisticsNumber();
                if(EmptyUtils.isEmpty(returnLogisticsId) || EmptyUtils.isEmpty(returnLogisticsNumber)){
                    return error("暂无物流信息");
                }
                json = k100Utils.queryTrack(returnLogisticsId, returnLogisticsNumber);
                JSONObject jsonObject = JSON.parseObject(json);
                String status = String.valueOf(jsonObject.get("status"));
                if("200".equals(status)){
                    redisUtils.set("return_logistics_" + orderPartsId, json, 1800);
                    orderParts = new ZsyhServiceOrderParts();
                    orderParts.setId(orderPartsId);
                    orderParts.setReturnLogisticsJson(json);
                    zsyhServiceOrderPartsService.updateZsyhServiceOrderParts(orderParts);
                }else{
                    String returnCode = String.valueOf(jsonObject.get("returnCode"));
                    if(!"200".equals(returnCode)){
                        String message = String.valueOf(jsonObject.get("message"));
                        return error(message);
                    }
                }
            }
        }

        return success("ok");
    }

    /**
     * 获取物流跟踪
     * @return
     * @throws Exception
     */
    @RequestMapping("/getLogisticsList")
    @ResponseBody
    public TableDataInfo getLogisticsList(String logId, String logNumber) throws Exception {
        String json  = k100Utils.queryTrack(logId, logNumber);
        //将json解析为list
        JSONObject jsonObject = JSONObject.parseObject(json);
        String logisStr = jsonObject.getString("data");
        List<Logis> logisList = JSON.parseArray(logisStr,Logis.class);
        return getDataTable(logisList);
    }
}


class Logis{

    private String context;

    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private Date ftime;

    public String getContext() {
        return context;
    }

    public void setContext(String context) {
        this.context = context;
    }

    public Date getFtime() {
        return ftime;
    }

    public void setFtime(Date ftime) {
        this.ftime = ftime;
    }
}

